<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传表单</title>
    <script src="//cdn.bootcss.com/jquery/2.2.0/jquery.min.js"></script>
    <script src="//cdn.bootcss.com/jquery.form/3.51/jquery.form.js"></script>
</head>
<body>
    <form id="upform" action="http://up.imgapi.com/" enctype="multipart/form-data" method="post">
        <input name="Token" id = "token" value="" type="hidden">
        <input type="file" name="file" id="selectimage" onchange="upload();">
        <button type="submit">上传</button>
    </form>


<script>
    $("#upform").ajaxForm(function(data,status){
        if(status == "success"){
            var linkurl = data.linkurl;
            var turl = data.t_url;
            selectimage.removeAttribute("disabled");
            var a = document.createElement('a');
            a.target = '_blank';
            a.className = 'imgsrc';
            a.href = linkurl
            a.innerHTML='<div class="showimage box-shadow" style="background-image:url('+turl+');"></div>'
            $('body').append('<img src="'+turl+'" />');
            console.log(data);
        }
        else{
            alert('上传错误！请重新上传图片。');
        }
    });
    window.onload = function(){
        //textarea.style.cssText = "background-image: url(http://ww2.sinaimg.cn/large/a15b4afegw1f0op3ut36wj21kw0idads.jpg);";
        $.ajax({
            type: 'GET',
            url: 'getToken.php?_r=' + Math.random(),
            dataType: 'json',
            cache: false,
            success:function (data) {
                var ttktoken = data.token;
                $('input[name="Token"]').val(ttktoken);
            }
        });
    }

    function upload(){
        //判断上传文件的类型
        filepath=$("#selectimage").val();
        var extStart=filepath.lastIndexOf(".");
        var ext=filepath.substring(extStart,filepath.length).toUpperCase();
        if(ext!=".BMP"&&ext!=".PNG"&&ext!=".GIF"&&ext!=".JPG"&&ext!=".JPEG"){
            alert("这不是一个正确的图片");
            return false;
        }
        $("#upform").submit();
        selectimage.disabled='disabled';
    };

</script>
</body>
</html>